<template>
  <div class="ai-chat-container">
    <div class="chat-header">
      <h2>AI智能问答</h2>
      <el-button type="danger" @click="clearHistory">清空历史记录</el-button>
    </div>
    
    <div class="chat-layout">
      <!-- 历史记录侧边栏 -->
      <div class="history-sidebar">
        <h3>历史记录</h3>
        <el-menu
          :default-active="activeHistory"
          @select="selectHistory"
          class="history-menu">
          <el-menu-item 
            v-for="record in chatHistory" 
            :key="record.id" 
            :index="record.id.toString()">
            <el-icon><ChatLineSquare /></el-icon>
            <span>{{ record.question.substring(0, 20) }}{{ record.question.length > 20 ? '...' : '' }}</span>
          </el-menu-item>
        </el-menu>
      </div>
      
      <!-- 聊天主区域 -->
      <div class="chat-main">
        <div class="chat-messages" ref="chatMessages">
          <div 
            v-for="msg in messages" 
            :key="msg.id" 
            :class="['message', msg.role]">
            <div class="message-content">
              <div class="avatar">
                <el-avatar :icon="msg.role === 'user' ? 'User' : 'Promotion'" />
              </div>
              <div class="content">
                <div class="text">{{ msg.content }}</div>
                <div class="time">{{ msg.time }}</div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="chat-input">
          <el-input
            v-model="userInput"
            type="textarea"
            :rows="3"
            placeholder="请输入您的问题，例如：图书馆开放时间是什么时候？"
            @keyup.enter="sendMessage"
          ></el-input>
          <div class="input-actions">
            <el-button 
              type="primary" 
              @click="sendMessage" 
              :disabled="!userInput.trim() || loading"
              :loading="loading">
              发送
            </el-button>
            <el-button @click="generateStudyMaterial">生成学习资料</el-button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 学习资料生成对话框 -->
    <el-dialog v-model="studyDialogVisible" title="学习资料生成" width="50%">
      <el-form :model="studyForm" label-width="120px">
        <el-form-item label="学习需求">
          <el-input 
            v-model="studyForm.demand" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入学习需求，例如：生成高等数学第三章复习提纲">
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="studyDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmGenerateStudyMaterial"
            :loading="studyLoading">
            生成
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ChatLineSquare } from '@element-plus/icons-vue'

export default {
  name: 'AiChat',
  components: {
    ChatLineSquare
  },
  data() {
    return {
      activeHistory: '',
      chatHistory: [
        { id: 1, question: '图书馆开放时间是什么时候？', time: '2024-10-20 10:30' },
        { id: 2, question: '如何申请奖学金？', time: '2024-10-19 15:45' },
        { id: 3, question: '生成高等数学第一章复习提纲', time: '2024-10-18 09:15' }
      ],
      messages: [
        { id: 1, role: 'assistant', content: '您好！我是校园智能助手，有什么我可以帮您的吗？', time: '2024-10-20 10:30' }
      ],
      userInput: '',
      loading: false,
      studyDialogVisible: false,
      studyLoading: false,
      studyForm: {
        demand: ''
      }
    }
  },
  methods: {
    async sendMessage() {
      if (!this.userInput.trim() || this.loading) return
      
      // 添加用户消息
      const userMessage = {
        id: Date.now(),
        role: 'user',
        content: this.userInput,
        time: new Date().toLocaleString()
      }
      this.messages.push(userMessage)
      
      // 清空输入框
      const question = this.userInput
      this.userInput = ''
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom()
      })
      
      try {
        this.loading = true
        
        // 模拟AI回复延迟
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 添加AI回复
        const aiResponse = {
          id: Date.now() + 1,
          role: 'assistant',
          content: this.generateMockResponse(question),
          time: new Date().toLocaleString()
        }
        this.messages.push(aiResponse)
        
        // 添加到历史记录
        this.chatHistory.unshift({
          id: Date.now(),
          question: question,
          time: new Date().toLocaleString()
        })
        
        // 滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      } catch (error) {
        this.$message.error('发送消息失败')
      } finally {
        this.loading = false
      }
    },
    generateMockResponse(question) {
      const responses = {
        '图书馆': '图书馆开放时间为周一至周五 8:00-22:00，周末 9:00-17:00。',
        '奖学金': '奖学金申请需要满足绩点3.0以上，无违纪记录，详情请查看奖学金申报模块。',
        '食堂': '一食堂营业时间为 6:30-21:00，二食堂营业时间为 7:00-21:30。',
        '宿舍': '宿舍晚上23:00关门，请按时回宿舍。',
        '默认': '这是一个模拟回复。如果您有具体问题，请详细描述，我会尽力帮助您。'
      }
      
      for (const key in responses) {
        if (question.includes(key)) {
          return responses[key]
        }
      }
      return responses['默认']
    },
    scrollToBottom() {
      const container = this.$refs.chatMessages
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    },
    selectHistory(index) {
      this.activeHistory = index
      const record = this.chatHistory.find(item => item.id == index)
      if (record) {
        this.$message.info(`选择了历史记录: ${record.question}`)
      }
    },
    clearHistory() {
      this.$confirm('确定要清空所有聊天记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.chatHistory = []
        this.messages = [
          { id: 1, role: 'assistant', content: '您好！我是校园智能助手，有什么我可以帮您的吗？', time: new Date().toLocaleString() }
        ]
        this.$message.success('聊天记录已清空')
      }).catch(() => {
        // 取消操作
      })
    },
    generateStudyMaterial() {
      this.studyForm.demand = ''
      this.studyDialogVisible = true
    },
    async confirmGenerateStudyMaterial() {
      if (!this.studyForm.demand.trim()) {
        this.$message.warning('请输入学习需求')
        return
      }
      
      try {
        this.studyLoading = true
        
        // 模拟生成学习资料
        await new Promise(resolve => setTimeout(resolve, 1500))
        
        this.$message.success('学习资料已生成，请在文件下载区查看')
        this.studyDialogVisible = false
      } catch (error) {
        this.$message.error('生成学习资料失败')
      } finally {
        this.studyLoading = false
      }
    }
  },
  mounted() {
    this.scrollToBottom()
  }
}
</script>

<style scoped>
.ai-chat-container {
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: white;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.chat-layout {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.history-sidebar {
  width: 250px;
  background: #f5f7fa;
  border-right: 1px solid #e4e7ed;
  padding: 15px;
  overflow-y: auto;
}

.history-sidebar h3 {
  margin-top: 0;
  margin-bottom: 15px;
}

.history-menu {
  border: none;
  background: transparent;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: #f9f9f9;
}

.message {
  margin-bottom: 20px;
}

.message-content {
  display: flex;
  align-items: flex-start;
}

.message.user .message-content {
  flex-direction: row-reverse;
}

.message.user .content {
  background: #409eff;
  color: white;
  margin-right: 10px;
}

.message.assistant .content {
  background: white;
  color: #333;
  margin-left: 10px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.avatar {
  flex-shrink: 0;
}

.content {
  padding: 10px 15px;
  border-radius: 8px;
  max-width: 70%;
}

.time {
  font-size: 12px;
  margin-top: 5px;
  opacity: 0.8;
}

.chat-input {
  padding: 20px;
  background: white;
  border-top: 1px solid #e4e7ed;
}

.input-actions {
  margin-top: 15px;
  text-align: right;
}
</style>